package com.raysun.androidbase.service.extension

import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.HandlerThread
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.os.Messenger
import android.os.Process
import android.widget.Toast

class MessengerService : Service() {

    private lateinit var messenger: Messenger

    private var serviceHandler: ServiceHandler? = null

    private val clientList = emptyList<Messenger>().toMutableList()

    inner class ServiceHandler(
        context: Context,
        looper: Looper,
        private val applicationContext: Context = context.applicationContext,
    ) : Handler(looper) {
        override fun handleMessage(msg: Message) {
            if (msg.what == 990923) {
                msg.replyTo?.let {
                    clientList.add(it)
                }
            } else {
                val message = Message.obtain().apply {
                    what = msg.what
                }
                clientList[0].send(message)
            }
            Toast.makeText(applicationContext, "what = ${msg.what}", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onCreate() {
        HandlerThread("Messenger", Process.THREAD_PRIORITY_BACKGROUND).apply {
            start()

            serviceHandler = ServiceHandler(this@MessengerService, looper)
            messenger = Messenger(serviceHandler)
        }
    }

    override fun onBind(intent: Intent?): IBinder {
        return messenger.binder
    }
}